<template>
  <el-dialog
    :title="title + '房产'"
    :visible="dialogVisible"
    width="50%"
    @close="closeFn"
  >
    <!-- 表单 -->
    <el-form ref="formData" :model="formData" status-icon :rules="rules" label-width="100px" class="demo-formData">
      <el-form-item label="经纪" prop="agent">
        <el-select v-model="formData.agent">
          <el-option v-for="item in agentList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="formData.category">
          <el-option v-for="item in categoryList" :key="item.id" :label="item.title" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="标签">
        <!-- 标签组件 -->
        <AddTags ref="tagsRef" />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-row type="flex">
          <el-cascader
            ref="cascader"
            :options="districtList"
            @change="handleChange"
          />
          <el-input v-model="formData.address" placeholder="请输入内容" class="input-with-select" style="width: 200px" />
        </el-row>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="formData.price" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="formData.desc" type="textarea" />
      </el-form-item>
      <el-form-item label="内容" />
      <el-form-item label="介绍图片">
        <!-- 图片上传组件 -->
        <ImageUpload ref="photosRef" img-type="photos" />
      </el-form-item>
      <el-form-item label="封面">
        <!-- 图片上传组件 -->
        <ImageUpload ref="imageRef" img-type="image" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="confirmFn">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import AddTags from './add-tags.vue'
import { getAgents } from '@/api/agents'
import { getCategories } from '@/api/categories'
import { getDistrict, addProperty, getPropertyDetail, updatePropertyDetail } from '@/api/property'
export default {
  components: {
    AddTags
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        agent: '',
        category: '',
        title: '',
        tags: '',
        address: '',
        price: '',
        desc: '',
        photos: '',
        image: ''
      },
      rules: {
        agent: [{ required: true, message: '请选择经纪', trigger: 'change' }],
        category: [{ required: true, message: '请选择分类', trigger: 'change' }],
        title: [{ required: true, message: '请选择', trigger: 'blur' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        desc: [{ required: true, message: '请输入房产描述', trigger: 'blur' }]
      },
      agentList: [],
      categoryList: [],
      // 行政区域列表
      districtList: [],
      curId: null,
      title: '新增'
    }
  },
  async created() {
    // 获取经纪列表
    const res = await getAgents()
    this.agentList = res.data
    // console.log(this.agentList)
    // 获取分类列表
    const result = await getCategories()
    this.categoryList = result.data
    // console.log(this.categoryList)

    // 高德地图api 方法2 解决跨域问题
    fetch('https://restapi.amap.com/v3/config/district?parameters&key=31a4f80b4b09aeac923c81d94386beb6&subdistrict=3', {
      method: 'get'
    }).then(async(res) => {
      console.log()
      const data = await res.json()
      const list = data.districts[0].districts
      this.districtList = this.formatDistrictList(list, 'province')
    })

    // 方法1（不能设置请求头） 否则存在跨域问题 --解决：在请求拦截器中设置一个属性值判断，是否给请求配置请求头
    // 获取行政区域列表
    // const key = '31a4f80b4b09aeac923c81d94386beb6'
    // const areaResult = await getDistrict({
    //   key,
    //   subdistrict: 3
    // })
    // const list = areaResult.data.districts[0].districts
    // this.districtList = this.formatDistrictList(list, 'province')
    // console.log(this.districtList)
  },
  methods: {
    // 根据id获取房产的详情并回显
    async getPropertyDetail(id) {
      const res = await getPropertyDetail(id)
      console.log(res.data)
      this.formData = res.data
      this.formData = {
        ...res.data,
        category: res.data.category.id ? res.data.category.id : res.data.category
      }
      // 回显标签
      this.$refs.tagsRef.dynamicTags = res.data.tags
      // 回显图片
      res.data.photos.forEach((item, index) => {
        this.$refs.photosRef.fileList.push({
          uid: index,
          url: item ? item.url : null
        })
      })
      // 回显封面
      this.$refs.imageRef.fileList.push({
        uid: 1,
        url: res.data.image
      })
      // console.log(this.formData)
    },
    // 关闭弹窗
    closeFn() {
      this.$emit('update:dialogVisible', false)
      // 重置表单
      this.$refs.formData.resetFields()
      this.$refs.imageRef.fileList = []
      this.$refs.photosRef.fileList = []
      this.$refs.tagsRef.dynamicTags = []
    },
    // 确定事件
    async confirmFn() {
      // 获取标签
      const tags = this.$refs.tagsRef.dynamicTags
      // 获取介绍图片
      const photos = []
      this.$refs.photosRef.fileList.forEach((item) => {
        photos.push(item.url)
      })
      // console.log('photos', photos)
      // 获取封面
      const image = this.$refs.imageRef.fileList[0] ? this.$refs.imageRef.fileList[0].url : ''
      // console.log('image', image)
      // 准备数据
      this.formData = {
        ...this.formData,
        photos,
        image,
        tags
      }
      console.log(this.formData)
      try {
        await this.$refs.formData.validate()
        if (this.formData.tags.length < 1) {
          return this.$message.info('请添加标签')
        }
        if (this.formData.photos.length < 1 || this.formData.image.length < 1) {
          return this.$message.info('请上传图片')
        }
        if (this.formData.id) {
          // 编辑
          await updatePropertyDetail(this.formData)
          this.$message.success('编辑成功')
        } else {
          // 新增
          await addProperty(this.formData)
          this.$message.success('新增成功')
        }
        // 关闭弹窗
        this.$emit('update:dialogVisible', false)
        // 刷新
        this.$emit('updateEvent')
      } catch (err) {
        console.log(err)
      }
    },
    // 级联列表影响输入框
    handleChange(val) {
      console.log(val)
      this.formData.address = val.join('-')
      // console.log(this.formData.address)
    },
    // 格式化级联列表的数据
    formatDistrictList(arr, level) {
      const list = []
      arr.forEach((item) => {
        // pid值为空字符串的时候，表示当前部门为一级部门
        if (item.level === level) {
          // 当level为province，则意味着item.districts代表city那一级别
          // 同理level为city时，item.districts代表区县
          if (item.districts && level !== 'district') {
            item.children = level === 'province' ? this.formatDistrictList(item.districts, 'city') : this.formatDistrictList(item.districts, 'district')
            // console.log(item.districts)
          }
          // 把对象添加到数组中
          list.push({
            value: item.name,
            label: item.name,
            children: item.children
          })
        }
      })
      return list
    }
  }
}
</script>

<style>
</style>
